package thread;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author TaoTaojs
 * @date 2021/3/8 上午8:53
 * <p>Description</p>
 * <h2>功能描述</h2>
 *
 * <h3>主要功能：</h3>
 * <ol>
 *     <li></li>
 * </ol>
 * <h3>关联类</h3>
 * <p>参考链接：</p>
 * <h2>更新日志</h2>
 * [author]        [time]                      [version]          [desc]
 * TaoTaojs        2021/3/8 上午8:53             V1.0
 */
@SuppressWarnings("ALL")
public class ConcurrentHashMapDemo {

    private static volatile ConcurrentHashMap<Integer, List<Integer>> orgTree = new ConcurrentHashMap();

    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 4, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(5),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
//                        orgTree.put(r);
                        System.out.println("线程"+r.hashCode()+"创建");
                        //线程命名
                        Thread th = new Thread(r,"threadPool"+r.hashCode());
                        return th;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()) {

            @Override
            protected void beforeExecute(Thread t,Runnable r) {
//                System.out.println("准备执行：" + r.toString() + r.hashCode());
            }

            @Override
            protected void afterExecute(Runnable r,Throwable t) {
//                System.out.println("执行完毕：" + r.toString() + r.hashCode());
            }

            @Override
            protected void terminated() {
                System.out.println("线程池退出");
            }
        };
        for(int i=0;i<10000000;i++) {
            pool.execute(new ThreadTask(i));
        }
        System.out.println(orgTree);
//        pool.shutdown();
    }

    public static class TreeBean{
        private String name;
        private List<TreeBean> treeBeans;
    }

    public static class ThreadTask implements Runnable{
        private Integer index;

        public ThreadTask(Integer s) {
            index = s;
        }

        @Override
        public void run() {
            //让线程阻塞，使后续任务进入缓存队列
//                Thread.sleep(1000);
//                System.out.println("ThreadName:"+Thread.currentThread().getName());

            if (orgTree.get(index % 10000) == null) {
//                synchronized (orgTree) {
                if (orgTree.get(index % 10000) == null) {
                    orgTree.put(index % 10000, new CopyOnWriteArrayList<>());
                }
//                }
            }

            orgTree.get(index % 10000).add(index);

        }
    }

}
